package com.zhouxiaoge.filters;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 周明阳
 * mail:gqzmy@outlook.com
 * 时间:2018-04-09 10:35
 */

public class FormLoginFilter extends PathMatchingFilter {

    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            /*已经登录过*/
            return true;
        }
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        String loginUrl = "/login.jsp";
        if (pathsMatch(loginUrl, WebUtils.getPathWithinApplication(httpServletRequest))) {
            /*form表单提交*/
            if ("post".equalsIgnoreCase(httpServletRequest.getMethod())) {
                /*登录*/
                boolean login = login(httpServletRequest);
                if (login) {
                    String successUrl = "/test.jsp";
                    WebUtils.redirectToSavedRequest(httpServletRequest, httpServletResponse, successUrl);
                    return false;
                }
            }
            /*继续过滤器链*/
            return true;
        } else {
            /*保存当前地址并重定向到登录界面*/
            WebUtils.saveRequest(httpServletRequest);
            WebUtils.issueRedirect(httpServletRequest, httpServletResponse, loginUrl);
            return false;
        }
    }

    private boolean login(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        try {
            SecurityUtils.getSubject().login(new UsernamePasswordToken(username, password));
        } catch (Exception e) {
            request.setAttribute("shiroLoginFailure", e.getClass());
            return false;
        }
        return true;
    }
}
